from functools import cached_property, lru_cache
from collections import deque, defaultdict
from fastapi import FastAPI
from tortoise.contrib.fastapi import register_tortoise
import aioredis
from configs.config import DB_MYSQL_CONFIG, DB_REDIS_CONFIG
from settings import settings


async def sys_cache() -> aioredis.Redis:
    """
    系统缓存
    :return: cache 连接池
    """
    # 从URL方式创建redis连接池
    sys_cache_pool = aioredis.ConnectionPool.from_url(
        f"redis://{DB_REDIS_CONFIG['host']}:{DB_REDIS_CONFIG['port']}",
        db=DB_REDIS_CONFIG['db1'],
        encoding='utf-8',
        decode_responses=True
    )
    return aioredis.Redis(connection_pool=sys_cache_pool)


async def code_cache() -> aioredis.Redis:
    """
    系统缓存
    :return: cache 连接池
    """
    # 从URL方式创建redis连接池
    sys_cache_pool = aioredis.ConnectionPool.from_url(
        f"redis://{DB_REDIS_CONFIG['host']}:{DB_REDIS_CONFIG['port']}",
        db={DB_REDIS_CONFIG['db2']},
        encoding='utf-8',
        decode_responses=True
    )
    return aioredis.Redis(connection_pool=sys_cache_pool)


async def register_mysql(app: FastAPI):
    # 注册数据库
    register_tortoise(
        app,
        config=DB_MYSQL_CONFIG,
        generate_schemas=False,
        add_exception_handlers=False,
    )

class NodeMananger:

    class Node:
        __slots__ = ["next", "pre", "val"]
        
        def __init__(self, val):
            self.val = val
            self.next = None
            self.pre = None
    
    def __init__(self) -> None:
        self.nodes = {}
    
    def add_node(self, source, target):
        if not self.nodes.get(source):
            self.nodes[source] = self.Node(source)
        if not self.nodes.get(target):
            self.nodes[target] = self.Node(target)
        self.nodes[source].next = self.nodes[target]
        self.nodes[target].pre = self.nodes[source]
        
    def get_heads(self):
        head_nodes = [key for key, node in self.nodes.items() if node.pre is None]
        print(f"{len(self.nodes)} ======>")
        return head_nodes
